// pages/answer_card/answer_card.js
const app = getApp();
var WebIM = require('../../utils/WebIM.js')
var WebIM = WebIM.default
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: "", // app.globalData.URL,
    initialState: false, // 页面元素初始显示状态
    onlineState: false, //在线答题返回
    cutState: false, //试卷切割状态
    submitActive: false, //提交状态
    wholeActive: false, //全选状态
    task_id: null,
    paper_ids: '',
    problemArray: [], //未提交数据
    subProblemArray: [] //已提交数据
  },

  /**
   * 提交状态tab切换
   */
  switchStatus: function(e) {
    var _this = this,
      index = e.currentTarget.dataset.active;
    if (index == 0) {
      var _submitActive = true;
    } else {
      var _submitActive = false;
    }
    _this.setData({
      submitActive: _submitActive,
      initialState: false
    })
    _this.getAnswerInfo();
  },

  /**
   * 全选操作
   */
  allElection: function() {
    var _this = this,
      _wholeActive = _this.data.wholeActive,
      _problemArray = _this.data.problemArray;
    for (var i = 0; i < _problemArray.length; i++) {
      _problemArray[i].status = !_wholeActive
    }
    _this.setData({
      wholeActive: !_wholeActive,
      problemArray: _problemArray
    })
  },

  /**
   * 显示或隐藏习题
   */
  problemHidden: function(e) {
    var _this = this,
      _wholeActive = _this.data.wholeActive,
      index = e.currentTarget.dataset.index,
      arrName = e.currentTarget.dataset.name,
      _arr = _this.data[arrName];
    _arr[index].hidden = !_arr[index].hidden;
    if (arrName == 'problemArray') {
      _this.setData({
        problemArray: _arr
      })
    } else {
      _this.setData({
        subProblemArray: _arr
      })
    }

  },

  /**
   * 单选习题答案是否上传
   */
  aloneChoice: function(e) {
    var _this = this,
      _wholeActive = _this.data.wholeActive,
      _problemArray = _this.data.problemArray,
      index = e.currentTarget.dataset.index;
    _problemArray[index].status = !_problemArray[index].status;
    var k = 0;
    for (var i = 0; i < _problemArray.length; i++) {
      if (_problemArray[i].status != _wholeActive) {
        k++;
      }
    }
    if (k >= 0 && k < _problemArray.length) {
      _wholeActive = false;
    } else if (k == _problemArray.length) {
      _wholeActive = !_wholeActive;
    }
    _this.setData({
      problemArray: _problemArray,
      wholeActive: _wholeActive
    })
  },

  /**
   * 资源学习上报
   */
  getaddTaskLog: function(type, index) {
    var _this = this;
    var param = {
      resource_id: _this.data.problemArray[index].resource_id,
      type: type,
      task_id: _this.data.task_id,
      structure_id: _this.data.problemArray[index].structure_id,
      kmapping_id: _this.data.problemArray[0].kmapping_id
    };
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/addTaskLog?' + app.globalData.URLBOOL,
      dataType: 'json',
      method: 'GET',
      data: param,
      success: function(res) {
        var _res = res.data;
        if (_res.error_code == 0) {}
      }
    })
  },

  /**
   * 获取答题卡信息
   */
  getAnswerInfo: function() {
    var _this = this,
      _submitActive = _this.data.submitActive,
      _paper_ids = _this.data.paper_ids,
      _task_id = _this.data.task_id;
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    if (_submitActive) {
      var _type = 1;
      wx.request({
        url: app.globalData.URL + '/kmapping/WebAppAjax/getTopicStatusBySplitAndTask?' + app.globalData.URLBOOL,
        method: 'GET',
        data: {
          type: _type,
          paper_ids: _paper_ids,
          task_id: _task_id
        },
        success(res) {
          if (res.data.error_code == 0) {
            var _problemArray = res.data.data;
            for (var i = 0; i < _problemArray.length; i++) {
              _problemArray[i].hidden = false;
              var topics = _problemArray[i].topics;
              // var topicArr = [];
            }
            //wx.setStorageSync('problemArray', _problemArray)
            _this.setData({
              subProblemArray: _problemArray,
            })
            _this.fromCache(_problemArray);
          } else if (res.data.error_code == 10002) {
            wx.hideLoading();
            _this.setData({
              subProblemArray: []
            })
          }
          _this.setData({
            initialState: true
          })
        },
        error: function(res) {

        }
      })
    } else {
      var _type = 2;
      _this.notSubmitDataDeal();
    }
  },

  /**
   * 未提交数据处理
   */
  notSubmitDataDeal: function() {
    var _this = this,
      user_id = wx.getStorageSync('userId'),
      _paper_ids = _this.data.paper_ids,
      _task_id = _this.data.task_id,
      paper_arr = _paper_ids.split(',');
    wx.request({
      url: app.globalData.URL + '/kmapping/WebAppAjax/getTopicStatusBySplitAndTask?' + app.globalData.URLBOOL,
      method: 'GET',
      data: {
        type: 2,
        paper_ids: _paper_ids,
        task_id: _task_id
      },
      success(res) {
        if (res.data.error_code == 0) {
          var _problemArray = res.data.data;
          for (var i = 0; i < _problemArray.length; i++) {
            _problemArray[i].status = false;
            _problemArray[i].hidden = false;
            var topics = _problemArray[i].topics;
            for (var j = 0; j < topics.length; j++) {
              if (topics[j].user_answer_paper_status == 1) {
                _this.hxDealWith();
                _this.setData({
                  cutState: true
                })
              }
            }
          }
          // if (!_this.data.cutState) { //在试卷切割中之外的情况下,判断缓存中是否存在该数据,如果存在将缓存拿出来当使用,如果不存在,则将改数据存入缓存
          //   for (var i = 0; i < _problemArray.length; i++) {
          //     var problemStorage = wx.getStorageSync(user_id + '-' + _task_id + '-' + _problemArray[i].id);
          //     if (!problemStorage) {
          //       wx.setStorageSync(user_id + '-' + _task_id + '-' + _problemArray[i].id, [_problemArray[i]]);
          //     } else {
          //       problemStorage[0].status = false;
          //       problemStorage[0].hidden = false;
          //       _problemArray[i] = problemStorage[0]
          //     }
          //   }
          // }
          _this.setData({
            problemArray: _problemArray
          })
          for (var k = 0; k < _problemArray.length; k++) {
            _this.getaddTaskLog(2, k);
          }
          _this.fromCache(_problemArray);
        } else if (res.data.error_code == 10002) {
          wx.hideLoading();
          _this.setData({
            problemArray: []
          })
        }
        _this.setData({
          initialState: true
        })
      },
      error: function(res) {

      }
    })
  },

  /**
   * 将题目信息录入缓存
   */
  fromCache: function(problemArray) {
    var _this = this;
    wx.request({
      url: app.globalData.URL + '/kmapping/WeixinAppAjax/addTopicAnswerToCache?' + app.globalData.URLBOOL,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        topic_info: JSON.stringify(problemArray)
      },
      success: function(res) {
        var _res = res.data;
        if (_res.error_code == 0) {
          wx.hideLoading();
          var key = _res.data.key;
          console.log(key);
          _this.setData({
            key: key,
            initialState: true
          })
        }
      }
    })
  },

  /**
   *提交答案 
   */
  submitAnswer: function() {
    var _this = this,
      _problemArray = _this.data.problemArray,
      _kmapping_id = _problemArray[0].kmapping_id,
      _task_id = _this.data.task_id,
      _user_id = wx.getStorageSync('userId');
    var selection = [];
    for (var i = 0; i < _problemArray.length; i++) {
      if (_problemArray[i].status) {
        selection.push(i);
      }
    }
    if (selection.length == 0) {
      wx.showToast({
        title: '请选择试题上传',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    //var problemArray = wx.getStorageSync('problemArray');
    var problemArray = _this.data.problemArray;
    var _answer = [];
    var pages_ids = [];
    var notAnswer = false;
    for (var j = 0; j < selection.length; j++) {
      var index = selection[j];
      var topics = problemArray[index].topics;
      var answer = {
        paper_id: problemArray[index].id,
        answer: []
      };
      for (var k = 0; k < topics.length; k++) {
        var myAnswer = {
          "resource_type": 0,
          "answer": "",
          "topic_id": null
        };
        if (topics[k].answer_flag == 0) {
          notAnswer = true;
        }
        if (typeof topics[k].paper_answer.answer != 'undefined') {
          if (typeof topics[k].paper_answer.answer.resource != 'undefined') {
            if (typeof topics[k].paper_answer.answer.resource.format_image != 'undefined') {
              var format_image = [];
              for (let x = 0; x < topics[k].paper_answer.answer.resource.format_image.length; x++) {
                format_image.push(topics[k].paper_answer.answer.resource.format_image[x].md);
              }
              myAnswer.resource_mds = format_image.join();
              if (format_image.length) {
                myAnswer.resource_type = 1;
              }
            }
          }
          if (typeof topics[k].paper_answer.answer.stu_answer != 'undefined') {
            myAnswer.answer = topics[k].paper_answer.answer.stu_answer;
          }
        }
        // if (typeof topics[k].paper_answer.answer != 'undefined') {
        //   if (typeof topics[k].paper_answer.answer.resource != 'undefined') {
        //     if (typeof topics[k].paper_answer.answer.resource.format_image != 'undefined') {
        //       myAnswer.resource_type = topics[k].paper_answer.answer.resource_type;
        //       myAnswer.resource_mds = topics[k].paper_answer.answer.resource.format_image[0].md;
        //     }
        //   }
        //   myAnswer.answer = topics[k].paper_answer.answer.stu_answer;
        // } else {
        //   myAnswer.answer = '';
        // }
        myAnswer.topic_id = topics[k].id;
        pages_ids.push(topics[k].id);
        answer.answer.push(myAnswer);
      }
      _answer.push(answer);
    }
    console.log(_answer);
    if (notAnswer) {
      wx.showModal({
        title: '警告',
        content: '试题中有未作答的题目,是否确认提交?',
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              title: '答案上传中',
            })
            wx.request({
              url: app.globalData.URL + '/kmapping/WebAppAjax/submitAnswerByPapers?' + app.globalData.URLBOOL,
              method: 'GET',
              data: {
                user_id: _user_id,
                task_id: _task_id,
                answer: _answer,
                kmapping_id: _kmapping_id
              },
              success(res) {
                wx.hideLoading();
                if (res.data.error_code == 0) {
                  wx.showToast({
                    title: '成功',
                    icon: 'success',
                    duration: 2000
                  })
                  for (let i = 0; i < _answer.length; i++) {
                    wx.removeStorageSync(_user_id + '-' + _task_id + '-' + _answer[i].paper_id);
                  }
                  for (var x = 0; x < selection.length; x++) {
                    _this.getaddTaskLog(3, selection[x]);
                  }
                  _this.getAnswerInfo();
                } else {
                  wx.showToast({
                    title: res.data.error_msg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '是否提交答案?',
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              title: '答案上传中',
            })
            wx.request({
              url: app.globalData.URL + '/kmapping/WebAppAjax/submitAnswerByPapers?' + app.globalData.URLBOOL,
              method: 'GET',
              data: {
                user_id: _user_id,
                task_id: _task_id,
                answer: _answer,
                kmapping_id: _kmapping_id
              },
              success(res) {
                wx.hideLoading();
                if (res.data.error_code == 0) {
                  wx.showToast({
                    title: '成功',
                    icon: 'success',
                    duration: 2000
                  })
                  for (let i = 0; i < _answer.length; i++) {
                    wx.removeStorageSync(_user_id + '-' + _task_id + '-' + _answer[i]);
                  }
                  for (var x = 0; x < selection.length; x++) {
                    _this.getaddTaskLog(3, selection[x]);
                  }
                  _this.getAnswerInfo();
                } else {
                  wx.showToast({
                    title: res.data.error_msg,
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })
    }
  },

  /**
   * 开启环信消息接收
   */
  hxDealWith: function() {
    var _this = this;
    WebIM.conn.listen({
      onTextMessage: function(message) {
        if (message) {
          var ext = JSON.parse(message.ext.ext);
          if (ext.msg_type == 28) {
            var messageData = JSON.parse(ext.msg_content);
            var task_id = messageData.task_id,
              paper_id = messageData.resource_id,
              key = messageData.key;
            app.dealMessage(key, task_id, paper_id);
            _this.setData({
              cutState: false
            })
            //WebIM.conn.close();
          }
        }
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    _this.setData({
      url: app.globalData.URL,
      paper_ids: options.paper_ids,
      task_id: options.task_id,
      kmapping_id: options.kmapping_id
    })
    _this.getAnswerInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this,
      user_id = wx.getStorageSync('userId'),
      problemArray = _this.data.problemArray,
      task_id = _this.data.task_id,
      paper_ids = _this.data.paper_ids,
      onlineState = _this.data.onlineState;
    if (onlineState) { //在线答题发回答题卡
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      _this.getAnswerInfo();
      _this.setData({
        onlineState: false //将返回标识初始化
      })
      // 2019-8-6 -- 改为在服务器做缓存
      // for (var i = 0; i < problemArray.length; i++) {
      //   wx.setStorageSync(user_id + '-' + task_id + '-' + problemArray[i].id, [problemArray[i]]);
      // }
      // _this.fromCache(problemArray);
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})